/*
* @Author: LiuShuang
* @Date:  2023-03-04 08:41:47
 * @FilePath: \network\src\utils\request.js
* @Description: In User Settings Edit
*/
import axios from 'axios';
import router from '../router/index.js'
import {MessageBox, Message, Loading} from 'element-ui'
import {getToken} from '@/utils/auth'
// 引入常量
import CONSTANT from '@/utils/constant'
// 引入本地存储
import {setJsonObjectToLocal, getJsonObjectFromLocal} from '@/utils/localstorage'

let loadingInstance = null								//这里是loading

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    timeout: 1000000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8', //默认的格式
        'Access-Control-Allow-Origin':'*'
    }
});

// request拦截器 拦截url
service.interceptors.request.use(config => {
    return interceptorUrl(config)
}, error => {
    Promise.reject(error)
})

// 拦截url地址 处理统一设置
function interceptorUrl(config) {
    loadingInstance = Loading.service({
        lock: true,
        text: 'loading...'
    })
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
        config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?';
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            var part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof (value) !== "undefined") {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config
}

// request拦截器  拦截token是否需要续签
service.interceptors.request.use(config => {
    return interceptorRefreshToken(config)
}, error => {
    Promise.reject(error)
})

// 拦截是否刷新token
async function interceptorRefreshToken(config) {
    // 验证token过期
    let localToken = getJsonObjectFromLocal(localStorage, CONSTANT.REFRESH_TOKEN);
    // console.log(localToken)
    if (localToken) {
        // 查看是否需要验签
        let time = new Date().getTime();
        if (localToken.expireTtl - time < CONSTANT.REFRESH_TIME) { // 刷新时间-当前时间 大于1分钟  就需要刷新token 续期token
            // 需要刷新
            await axios.get(process.env.VUE_APP_BASE_API + "/pri/auth/refresh_token?refreshToken="
                + localToken.refreshToken + "&token=" + localToken.token)
                .then(ret => {
                    if (ret.data.code == 0) {
                        localToken.expireTtl = ret.data.data.expireTTl;
                        localToken.refreshToken = ret.data.data.refreshToken;
                        setJsonObjectToLocal(window.sessionStorage, CONSTANT.REFRESH_TOKEN, localToken)
                    }
                }).catch(error => {
                    console.error('Error:', error);
                });;
        }
    }
    return config;
}

// 响应拦截器
service.interceptors.response.use(
    res => {
        loadingInstance.close()
        if (res.status == 200){
            if(res.data.code == 260005){
                MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    sessionStorage.clear();
                    router.push('/login');
                })
            }else{
                return Promise.resolve(res.data);
            }
        }else{
            return Promise.reject(res);
        }
    },
    error => {
        loadingInstance.close()
        let {message} = error
        if (message == 'Network Error') {
            message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        Message({
            message: message,
            type: 'error',
            duration: 3 * 1000
        })
    }
)
export default service;
